<script lang="ts" setup>
import { EducChatMessageItem, type MessageItem } from '@/common/components/educ-chat-room/educ-message-item';
import { MessageSender, MessageSenderAvatar, MessageSenderName } from '@/common/enums/message-sender';
import { useUserStore } from '@/common/stores/index';
import { SettingOutlined, UnorderedListOutlined } from '@ant-design/icons-vue';
import dayjs from 'dayjs';
import relativeTime from 'dayjs/plugin/relativeTime';
import type { CSSProperties } from 'vue';
dayjs.extend(relativeTime)

interface ChatMessageItem extends MessageItem {
  id: number | string
}

/**消息列表 */
const messageList = ref<ChatMessageItem[]>([])

/**添加信息 */
const addMessage = (message: ChatMessageItem) => messageList.value.push(message)

/**用户唯一id */
const userUniqueId = ref(useUserStore().userInfo?.user ?? useId())

const { connect, disconnect, send } = useWebSocket({
  url: import.meta.env.EDUC_WEBSOCKET_URL,
  onMessage: (event) => {
    const id = useId()
    addMessage({
      id,
      sender: MessageSender.Other,
      message: event.data,
      nickname: MessageSenderName[MessageSender.Other],
      avatar: MessageSenderAvatar[MessageSender.Other],
    })
  }
})



const headerStyle: CSSProperties = {
  color: '#111',
  padding: '0 1.5rem',
  backgroundColor: '#fff',
}

const siderStyle: CSSProperties = {
  textAlign: 'center',
  backgroundColor: '#ffffff',
  display: 'flex',
  flexDirection: 'column',
  justifyContent: 'space-evenly',
  position: 'relative',
}

const hbg = ref(false)
// 用户输入的值
const inputValue = ref<string>('')
const chatContent = ref<HTMLElement | null>(null)
const value = ref<string>('')

// 侧边栏宽度的计算函数
const screenWidth = ref(0)
// 用于更新屏幕宽度的函数
const updateScreenSize = () => {
  screenWidth.value = window.innerWidth
}



// 根据屏幕宽度返回对应的侧边栏宽度值的计算函数
const computedWidth = () => {
  if (screenWidth.value >= 768) {
    return 250
  } else if (screenWidth.value >= 480) {
    return 200
  } else {
    return 0
  }
}

// 房间
const rooms = reactive([
  {
    id: 1,
    name: '社会边角料',
    introduce: '这是一间公共房间',
    portrait: 'src/assets/portrait/01.jpg',
    room: '已加入',
  },
  {
    id: 2,
    name: '技术交流群',
    introduce: '这是技术交流的地方',
    portrait: 'src/assets/portrait/02.jpg',
    room: '进房间',
  },
  {
    id: 3,
    name: '读书俱乐部',
    introduce: '分享阅读心得和书籍推荐',
    portrait: 'src/assets/portrait/03.jpg',
    room: '进房间',
  },
  {
    id: 4,
    name: '健身爱好者',
    introduce: '讨论健身技巧和健康饮食',
    portrait: 'src/assets/portrait/04.jpg',
    room: '进房间',
  },
  {
    id: 5,
    name: '旅行分享会',
    introduce: '分享旅行故事和攻略',
    portrait: 'src/assets/portrait/05.jpg',
    room: '进房间',
  },
  {
    id: 6,
    name: '摄影爱好者',
    introduce: '交流摄影技巧和作品展示',
    portrait: 'src/assets/portrait/06.jpg',
    room: '进房间',
  },
])

// 点击加入房间
const onJointheroom = () => {
  open.value = true
}

const open = ref<boolean>(false)

const handleOk = (e: MouseEvent) => {
  console.log(e)
  open.value = false
}

// 点击进入房间
const onRoouButton = (index: number) => {
  console.log(index)
}

// 点击发送内容
const onchatroot = () => {
  if (inputValue.value.trim()) {
    const id = useId()

    addMessage({
      id,
      sender: MessageSender.Self,
      message: inputValue.value,
      nickname: MessageSenderName[MessageSender.Self],
      avatar: MessageSenderAvatar[MessageSender.Self],
    })


    send(inputValue.value)
    inputValue.value = '' // 清空输入框
  }
}






// 在组件挂载时，获取初始屏幕宽度，并添加窗口大小变化的监听
onMounted(() => {
  connect()
  updateScreenSize()
  window.addEventListener('resize', updateScreenSize)
})

// 在组件销毁前，移除窗口大小变化的监听，避免内存泄漏
onBeforeUnmount(() => {
  disconnect()
  window.removeEventListener('resize', updateScreenSize)
})


</script>

<template>
  <a-space direction="vertical" :style="{ width: '100%', height: 'auto' }">
    <a-layout style="height: 80vh">
      <a-layout-sider :style="siderStyle" :width="computedWidth()">
        <a-button type="primary" size="large" @click="onJointheroom" style="width: 90%; margin: 10px">加入房间</a-button>
        <!-- 输入房间号 -->
        <a-modal v-model:open="open" title="请输入房间号！" @ok="handleOk">
          <a-input v-model:value="value" placeholder="输入房间号" />
        </a-modal>
        <div class="room">
          <p>公共房间</p>
          <div class="room-lists">
            <div class="room-list" v-for="(item, index) in rooms" :key="item.id">
              <img :src="item.portrait" alt="" />
              <div style="width: 40%">
                <p>{{ item.name }}</p>
                <p>{{ item.introduce }}</p>
              </div>
              <div>
                <a-button :type="item.room === '已加入' ? 'dashed' : 'primary'" @click="onRoouButton(index)">{{ item.room
                  }}</a-button>
              </div>
            </div>
          </div>
        </div>
        <p class="set">
          <span class="set-span">
            <SettingOutlined />
          </span>设置
        </p>
      </a-layout-sider>
      <a-layout>
        <!-- header 导航 -->
        <a-layout-header :style="headerStyle">
          <div class="room-name">
            <p>社会边角料（3）</p>
            <button class="icon" @click="hbg = !hbg">
              <UnorderedListOutlined />
            </button>
          </div>
        </a-layout-header>
        <!-- content 内容 -->
        <a-layout-content class="chat-content" ref="chatContent" v-auto-scroll:bottom>
          <!-- <educ-other-users />
          <div v-for="(message, index) in chatMessages" :key="index">
            <educ-current-user :dataToPass="message" />
          </div> -->
          <EducChatMessageItem v-for="message in messageList" :message="message" :key="message.id" />

        </a-layout-content>
        <!-- footer 输入框 -->
        <a-layout-footer>
          <div class="input-box">
            <a-input v-model:value="inputValue" :bordered="false" placeholder="请输入内容..." @pressEnter="onchatroot" />
            <a-button type="primary" @click="onchatroot">发送</a-button>
          </div>
        </a-layout-footer>
      </a-layout>
    </a-layout>
  </a-space>

  <div class="root" v-show="hbg">
    <div class="room-lists">
      <div class="room-list" v-for="item in rooms" :key="item.id">
        <img :src="item.portrait" alt="" />
        <div>
          <p>{{ item.name }}</p>
          <p>{{ item.introduce }}</p>
        </div>
        <div>
          <a-button :type="item.room === '已加入' ? 'dashed' : 'primary'">{{
            item.room
          }}</a-button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.icon {
  margin-left: 0.625rem;
  font-size: 1.25rem;
  cursor: pointer;
  background-color: transparent;
  border: none;
}

// 房间相关样式
.room {
  height: 100%;
  overflow: hidden;

  &>p {
    margin-bottom: 0.625rem;
    font-size: 0.75rem;
    color: #999;
  }

  &-lists {
    height: 60%;
    overflow-y: auto;

    .room-list {
      display: flex;
      align-items: center;
      justify-content: space-evenly;
      padding: 0.125rem;
      margin-bottom: 1.25rem;

      img {
        width: 2.5rem;
        height: 2.5rem;
        object-fit: cover;
        border-radius: 50%;
      }

      p {
        padding: 0.3125rem 0;
        margin: 0;
        overflow: hidden;
        text-align: left;
        text-overflow: ellipsis;
        white-space: nowrap;

        &:nth-child(2) {
          font-size: 0.625rem;
          color: #999;
        }
      }
    }
  }
}

.room-name {
  display: flex;
  align-items: center;
  justify-content: space-between;

  span {
    display: none;
  }
}

// 内容样式
.chat-content {
  max-height: calc(80vh - 50px);

  /* 设置合理的高度 */
  overflow-y: auto;
}

// 输入框相关样式
.input-box {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: space-between;
  width: 100%;
  height: 150px;
  padding: 20px;
  background-color: white;
}

.ant-layout .ant-layout-footer {
  padding: 0;
}

// 设置相关样式
.set {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 1.25rem 0;
  line-height: 1.25rem;
  color: #111;
  background-color: #fff;

  &-span {
    margin-right: 0.625rem;
  }
}

@media screen and (width <=48rem) {
  img {
    display: none;
  }
}

@media screen and (width <=30rem) {
  .room-name {
    span {
      display: block;
    }
  }

  .btn {
    margin: 0.625rem;
  }
}

.root {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 909;
  height: 100%;
  padding: 1.25rem;
  overflow-y: auto;
  background-color: #f5f5f5;
}
</style>
